package com.team6.cet.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.team6.cet.entity.IStatusMessage;
import com.team6.cet.entity.OrdinaryUser;
import com.team6.cet.entity.ResponseResult;
import com.team6.cet.service.OrdinaryUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
 

@CrossOrigin(origins = "*")
@RestController
@EnableAutoConfiguration
@Api(tags = "普通用户api")
@Validated
/**
 * 用户信息控制类
 */
public class OrdinaryUserController {
	@Autowired
	private OrdinaryUserService userService;
	private static final Logger logger = LoggerFactory.getLogger(OrdinaryUserController.class);
	@Value("${web.upload-path}")
	/**
	 * 文件路径
	 */
	private String uploadPath;

	
	   @GetMapping("/getUserInfo")  
	    //实现数据库分页查询 前端结合layui
	    public Object getUserInfo(@RequestParam(value = "page", required = false) int page,
				@RequestParam(value = "limit", required = false) int limit) {  
	    	
	       List<OrdinaryUser> user = userService.getUserInfo((page-1)*limit,limit);  
	       Map map=new HashMap();
	       map.put("code", 0);
	       map.put("data", user);
	       map.put("count",userService.findUserNum());      
	        return map;  
	    } 
	// 登录页面
	@PostMapping(value = "/login")
	public ResponseResult login(@ApiParam(required = true, value = "添加考试信息")@RequestBody @Valid OrdinaryUser user) {

		ResponseResult responseResult = new ResponseResult();
		responseResult.setCode(IStatusMessage.SystemStatus.ERROR.getCode());
		if (null == user) {
			responseResult.setCode(IStatusMessage.SystemStatus.PARAM_ERROR.getCode());
			responseResult.setMessage("请求参数有误，请您稍后再试");
			logger.debug("用户登录，结果=responseResult:" + responseResult);
			return responseResult;
		}
		// 用户是否存在
		OrdinaryUser existUser = this.userService.getOrdinarybyEmail(user.getOrdinaryUserEmail());
		// 是否锁定
		if (existUser == null) {
			responseResult.setMessage("该用户不存在，请您联系管理员");
			logger.debug("用户登录，结果=responseResult:" + responseResult);
			return responseResult;
		} else {
			boolean flag = false;
			 
			 
				OrdinaryUser cuser= userService.FindByEmailandPassword(user.getOrdinaryUserEmail(),DigestUtils.md5Hex(user.getOrdinaryUserPassword()));
			 
				if (cuser!=null) {
					/* 获得请求后的状态码 */
					responseResult.setCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
					responseResult.setObj(cuser);
				}
				else {
					/* 获得请求后的状态码 */
					responseResult.setCode(IStatusMessage.SystemStatus.ERROR.getCode());
					responseResult.setMessage("密码错误！");
				}

			return responseResult;
		}
	}
 

	/**
	 * 登出系统，注销用户信息
	 */
	@GetMapping("/logout")
	public void logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			System.out.println("注销成功");
		}
	}

	/**
	 * 添加用户信息
	 */
	@PostMapping("/addUserInfo")
	public ResponseResult addUserInfo(OrdinaryUser user, MultipartFile[] files) {
		 ResponseResult responseResult = new ResponseResult();
		 
		OrdinaryUser ordinaryUser=userService.getOrdinarybyEmail(user.getOrdinaryUserEmail());
		System.out.println(user.getOrdinaryUserEmail());
		
		if (ordinaryUser!=null) {
			System.out.println(ordinaryUser.getOrdinaryUserEmail());
			responseResult.setCode(IStatusMessage.SystemStatus.ERROR.getCode());
			responseResult.setMessage("邮箱存在！");	 
		}
		else {
		String imgs = "";
		String name = null;
		int len = files.length;
		System.out.println(files.length);
		if (files != null && files.length >= 1) {
			while (len > 0) {
				len--;
				BufferedOutputStream bw = null;
				try {
					String fileName = files[len].getOriginalFilename();
					// 判断是否有文件且是否为图片文件
					if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {

						name = UUID.randomUUID().toString() + getFileType(fileName);
						File outFile = new File(uploadPath + "/" + name);

						//imgs += name + ",";   上传多个文件用 “，”隔开。
						imgs+=name;
						FileUtils.copyInputStreamToFile(files[len].getInputStream(), outFile);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (bw != null) {
							bw.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		user.setOrdinaryUserImg(imgs);
		user.setOrdinaryUserPassword(DigestUtils.md5Hex(user.getOrdinaryUserPassword()));
		userService.insert(user);
			responseResult.setCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
			responseResult.setMessage("添加成功");
		}
		return responseResult;
	}

	private Boolean isImageFile(String fileName) {
		String[] img_type = new String[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
		if (fileName == null) {
			return false;
		}
		fileName = fileName.toLowerCase();
		for (String type : img_type) {
			if (fileName.endsWith(type)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @param fileName
	 * @return
	 */
	private String getFileType(String fileName) {
		if (fileName != null && fileName.indexOf(".") >= 0) {
			return fileName.substring(fileName.lastIndexOf("."), fileName.length());
		}
		return "";
	}

	/**
	 * 根据id查询用户信息
	 */
	@GetMapping("/getUserAndRoles")
	public Map<String, Object> getUserAndRoles(@RequestParam("id") Integer id) {

		Map<String, Object> map = new HashMap<>();
		try {
			if (null == id) {
				map.put("msg", "请求参数有误，请您稍后再试");
				return map;
			}
			// 查询用户
			OrdinaryUser urvo = userService.getUserInfo(id);
			if (null != urvo) {
				map.put("user", urvo);
				// 获取用户头像数据
				String imgs = urvo.getOrdinaryUserImg();
				List files = new LinkedList<>();
				if (imgs == null) {
					System.err.println(urvo.getOrdinaryUserImg() + "okok");
				} else {
						String img[] = imgs.split(",");
						for (int i = 0; i < img.length; i++) {
							files.add(img[i]);
						}
				}
				map.put("files", files);
				map.put("msg", "ok");
			} else {
				map.put("msg", "查询用户信息有误，请您稍后再试");
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "查询用户错误，请您稍后再试");
		}
		return map;
	}

	/**
	 * 更新用户信息
	 */
	@PostMapping("/updataUserInfo")
	public Object updataUserInfo(OrdinaryUser user) {
		Map<String, Object> map = new HashMap<>();
		userService.updataUserINfo(user);
		map.put("data", "ok");
		return map;
	}

	/**
	 * 根据id删除用户信息
	 */
	@GetMapping("/delUserInfo")
	public Object del(@RequestParam(value = "Id", required = false) int id) {
		Map<String, Object> map = new HashMap<>();
		userService.del(id);
		map.put("data", "ok");
		return map;
	}
	
	@PostMapping("/upfile")
	public ResponseResult upfile(String  email,MultipartFile files) {
		 ResponseResult responseResult = new ResponseResult();
		 OrdinaryUser user=userService.getOrdinarybyEmail(email);
		 
		 String imgs = "";
		 String name = null;
		 
		 if (files != null ) {
				 
					BufferedOutputStream bw = null;
					try {
						String fileName = files.getOriginalFilename();
						// 判断是否有文件且是否为图片文件
						if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {

							name = UUID.randomUUID().toString() + getFileType(fileName);
							File outFile = new File(uploadPath + "/" + name);

							//imgs += name + ",";   上传多个文件用 “，”隔开。
							imgs+=name;
							FileUtils.copyInputStreamToFile(files.getInputStream(), outFile);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						try {
							if (bw != null) {
								bw.close();
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
		 user.setOrdinaryUserImg(imgs);
	     userService.updataUserINfo(user);
		  responseResult.setCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
		  responseResult.setMessage("添加成功");
		 return responseResult;
	}
}
